﻿using OA.Controllers;
using StackExchange.Profiling;
using StackExchange.Profiling.EntityFramework6;
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;

namespace OA
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            MiniProfilerEF6.Initialize();
        }

        protected void Application_BeginRequest()
        {
            MiniProfiler.Start();
        }

        protected void Application_EndRequest()
        {
            MiniProfiler.Stop();
        }

        protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
		{
			HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
			if(authCookie != null)
			{
				try
				{
					FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
					CurrentUserCookie user = Newtonsoft.Json.JsonConvert.DeserializeObject<CurrentUserCookie>(authTicket.UserData);
					user.GenericIdentity(authTicket.Name);
                    // 实体替换
					HttpContext.Current.User = user;
				}
				catch
				{
					return;
				}
			}
		}
    }
}
